package oop.ex3.filemanager;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.net.Socket;

import oop.ex3.protocol.ClientMessageSender;

public class UploadThread extends Thread {
	private static final boolean FAILURE = false;
	private String _fileName; //the name of the uploaded file.
	private File _file; // the uploaded file itself.
	private Socket _clientSocket;
	private DataInputStream _clientInput;
	private DataOutputStream _clientOutput;
	
	/**
	 * Creates a new UploadThread.
	 * Assigns fileName to be the UploadThread's file name,
	 * and creates the actual file to be uploaded.
	 * also creates input and output streams to communicate with the client.
	 * @param fileManager the fileManager creating the uploadThread.
	 * @param fileName the name of the file to be uploaded by this UploadThread.
	 * @param clientSocket the socket of the client that will receive the file. 
	 */
	public UploadThread(FileManager fileManager, 
							Socket clientSocket, String fileName){
		this._fileName=fileName;
		this._file = new File (fileManager.getFilePath(fileName));
		System.out.println("UPLOAD THREAD: created a new file");
		this._clientSocket = clientSocket;
		try {
			this._clientInput = new DataInputStream(this._clientSocket.getInputStream());
			System.out.println("UPLOAD THREAD: created inputStream");
			this._clientOutput = new DataOutputStream(this._clientSocket.getOutputStream());
		
		} catch (IOException e) {
			closeStreams();
		}
		
	}
	
	public String getFileName(){
		return this._fileName;
	}
	
	/**
	 * Closes this session's streams.
	 */
	private void closeStreams(){
		//TODO check for closing socket too or not
		try {
			this._clientInput.close();
			this._clientOutput.close();
			this._clientSocket.close();
		} catch (Exception e) {
			// TODO handle exception
		}
	}
	
	public void run(){
		
		if (ClientMessageSender.file(_clientOutput, this._file)==FAILURE){
			ClientMessageSender.error(_clientOutput);
			closeStreams();
			return;
		}
		closeStreams();
	}
	
}
